package cn.maihe.elg.operation.supports.system;

import cn.maihe.elg.operation.security.model.UserContext;
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Description
 * @Author WJH
 * @Date 2021/03/26
 */
@Component
@Slf4j
public class CommonMetaObjectHandler extends MetaObjectHandler {
    //创建时间 datetime
    private final static String GMTCREATE = "gmtCreate";
    //更新时间 datetime
    private final static String GMTMODIFIED = "gmtModified";
    /**
     * 创建用户
     */
    private final static String USERCREATE = "userCreate";
    /**
     * 更新用户
     */
    private final static String USERMODIFIED = "userModified";

    @Override
    public void insertFill(MetaObject metaObject) {
        Date curDate = new Date();
        if (metaObject.hasSetter(GMTCREATE)) {
            this.setFieldValByName(GMTCREATE, curDate, metaObject);
        }
        if (metaObject.hasSetter(GMTMODIFIED)) {
            this.setFieldValByName(GMTMODIFIED, curDate, metaObject);
        }
        String userName = getCurUserName();
        if (metaObject.hasSetter(USERCREATE)) {
            Object userCreate = this.getFieldValByName(USERCREATE, metaObject);
            if (StringUtils.isBlank((String) userCreate)) {
                this.setFieldValByName(USERCREATE, userName, metaObject);
            }
        }
        if (metaObject.hasSetter(USERMODIFIED)) {
            Object userModified = this.getFieldValByName(USERMODIFIED, metaObject);
            if (StringUtils.isBlank((String) userModified)) {
                this.setFieldValByName(USERMODIFIED, userName, metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(GMTMODIFIED)) {
            this.setFieldValByName(GMTMODIFIED, new Date(), metaObject);
        }
        if (metaObject.hasSetter(USERMODIFIED)) {
            this.setFieldValByName(USERMODIFIED, getCurUserName(), metaObject);
        }

    }

    private String getCurUserName() {
        try {
            Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (object instanceof UserContext) {
                UserContext userContext = (UserContext) object;
                return userContext == null ? "system" : userContext.getUsername();
            }
        } catch (Exception e) {
        }
        return "system";
    }
}
